package com.silverbox.sweeporder.service.index.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.silverbox.waimai.entity.TakeOutConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import com.silverbox.core.result.CoreResponse;
import com.silverbox.core.util.DateUtils;
import com.silverbox.core.util.StringUtils;
import com.silverbox.core.util.Utils;
import com.silverbox.shopper.dubboApi.goods.ShopperGoodsServiceApi;
import com.silverbox.shopper.dubboApi.info.ShopperInfoServiceApi;
import com.silverbox.shopper.dubboApi.order.OrderServiceApi;
import com.silverbox.shopper.entity.BusinessWhiteList;
import com.silverbox.shopper.entity.CupboardOrderRecord;
import com.silverbox.shopper.entity.DiningArea;
import com.silverbox.shopper.entity.ShopperConfig;
import com.silverbox.shopper.entity.ThirdUserInfo;
import com.silverbox.shopper.entity.extend.CategoryGoods;
import com.silverbox.shopper.entity.extend.DecorationShopConfigDetailExtend;
import com.silverbox.shopper.entity.extend.DiscountInfo;
import com.silverbox.shopper.entity.extend.GoodsExtendParam;
import com.silverbox.shopper.entity.extend.ShopperAndParent;
import com.silverbox.shopper.entity.extend.ShopperInfo;
import com.silverbox.sweeporder.common.AlipayServiceEnvConstants;
import com.silverbox.sweeporder.common.CommConstant;
import com.silverbox.sweeporder.common.Constants;
import com.silverbox.sweeporder.common.util.AlipayAPIClientFactory;
import com.silverbox.sweeporder.common.util.SweepOrderUtils;
import com.silverbox.sweeporder.controller.index.vo.DiscountInfoVO;
import com.silverbox.sweeporder.controller.index.vo.ShopperConfigExtend;
import com.silverbox.sweeporder.controller.shopcart.entryvo.SaveShopCartEntryVO;
import com.silverbox.sweeporder.controller.shopcart.outvo.SaveShopCartByUserVO;
import com.silverbox.sweeporder.controller.shopcart.outvo.SaveShopCartVO;
import com.silverbox.sweeporder.service.index.AuthService;
import com.silverbox.sweeporder.service.redis.RedisService;
import com.silverbox.sweeporder.service.shopcart.ShopCartService;
import com.silverbox.sweeporder.service.waimai.WaimaiOrderService;
import com.silverbox.waimai.dubboApi.goodscart.GoodsCartServiceApi;
import com.silverbox.waimai.dubboApi.order.WaimaiServiceApi;
import com.silverbox.waimai.entity.Waimai;
import com.silverbox.waimai.entity.extend.GoodsCartAndDetail;
import com.silverbox.waimai.entity.extend.WaimaiExtend;
import com.silverbox.waimai.entity.extend.WaimaiParam;

@Service
//@Transactional
public class AuthServiceImpl implements AuthService {

	@Autowired
	private ShopCartService shopCartService;
	
	@Autowired
	private RedisService<Serializable, Object> redisService;

	@Autowired
	private WaimaiOrderService waimaiOrderService;
	
	@Autowired
	private ShopperInfoServiceApi shopperInfoServiceApi;

	@Autowired
	private ShopperGoodsServiceApi shopperGoodsServiceApi;
	
	@Autowired
	private GoodsCartServiceApi goodsCartServiceApi;
	
	@Autowired
	private WaimaiServiceApi waimaiServiceApi;
	
	@Autowired
	private OrderServiceApi orderServiceApi;

	@Value("${sweepOrderVueUrl}")
	private String sweepOrderVueUrl;

	private static Logger logger = LoggerFactory.getLogger(IndexServiceImpl.class);

	@Override
	public String getGoodsShowPath(Integer storeId, Integer goodsId, Long sizeId, String buyerId, Integer authMode) {
		// 扫商品码错误页面
		String path = sweepOrderVueUrl + "/#/sweepfail";
		// 售罄时间
		String dateStart = DateUtils.getTodayStartTime();
		String dateEnd = DateUtils.getTodayEndTime();
		String nowDate = DateUtils.getNowTime();
		// 获取店铺信息数据
		ShopperInfo shopper = shopperInfoServiceApi.getShopperInfo(storeId, nowDate);
		if (shopper == null) {
			logger.error("商品二维码获取店铺信息失败获取店铺信息为=====" + shopper+"storeId="+storeId);
			return path;
		}
		GoodsExtendParam goodsExtendParam = new GoodsExtendParam();
		ShopperConfigExtend shopperConfigExt = null;
		/*// 获取redis店铺配置信息
		Object config = redisService.getObj(storeId + "_shopperConfig");
		ShopperConfigExtend shopperConfigExt = null;
		if (config == null) {
			// 查询店铺所有配置
			Map<String, Object> shopperConfig = shopperInfoServiceApi.getShopperAllConfig(storeId);
			// map转成对象
			shopperConfigExt = SweepOrderUtils.convertToShopperConfigVO(shopperConfig);
		} else {
			shopperConfigExt = (ShopperConfigExtend) config;
		}*/
		//获取店铺配置信息
		Map<String, Object> shopperConfig = shopperInfoServiceApi.getShopperAllConfig(storeId);
		if(shopperConfig==null){
			//店铺配置获取失败
			path ="/main.html#/error";
			return path;
		}
		// map转成对象
		shopperConfigExt = SweepOrderUtils.convertToShopperConfigVO(shopperConfig);
		redisService.setObj(storeId + "_shopperConfig", shopperConfigExt,24L,TimeUnit.HOURS);	
		// 查询是否先付后吃模式
		Integer isFirstPay = shopperConfigExt.getFirstPayMent();
		goodsExtendParam.setIsFirstPay(isFirstPay);
		goodsExtendParam.setStoreId(storeId);
		goodsExtendParam.setGoodsId(goodsId);
		goodsExtendParam.setSizeId(sizeId);
		goodsExtendParam.setStartDate(dateStart);
		goodsExtendParam.setEndDate(dateEnd);
		goodsExtendParam.setNowDate(nowDate);
		// 查询商品信息
		List<CategoryGoods> goodsList = shopperGoodsServiceApi.getGoodsInfoByGoodsId(goodsExtendParam);
		if (CollectionUtils.isEmpty(goodsList) || goodsList.get(0) == null) {
			// 扫商品码错误页面
			logger.error("扫商品二维码查询商品失败param" + JSONObject.toJSONString(goodsExtendParam));
			return path;
		}
		CategoryGoods goods = goodsList.get(0);
		// 当商品为无属性、单规格、不为套餐、且未售罄时直接加入购物车/暂时不考虑起卖数、累加数
		if (goodsList.size() == 1 && goodsList.get(0).getIsPackage() != 2 && goodsList.get(0).getIsProp() != 1
				&& goodsList.get(0).getIsSellOut() != 1) {
			SaveShopCartEntryVO goodsCartVO = new SaveShopCartEntryVO();

			goodsCartVO.setBuyCount(1d);
			goodsCartVO.setBuyPrice(goods.getPrice());
			goodsCartVO.setCategoryId(goods.getCategoryId());
			goodsCartVO.setCategoryName(goods.getCategoryName());
			goodsCartVO.setGoodsAddNum(goods.getMinAddUnit());
			goodsCartVO.setGoodsDesc("");
			goodsCartVO.setGoodsId(goods.getGoodsId());
			goodsCartVO.setGoodsName(goods.getGoodsName());
			goodsCartVO.setGoodsSellNum(goods.getMinSell());
			if (goods.getImagePath() == null) {
				goodsCartVO.setImagePath("res/imggoodspic.png");
			} else {
				goodsCartVO.setImagePath(goods.getImagePath());
			}
			if (goods.getIsPackage() == null) {
				goodsCartVO.setIsPackage(0);
			} else {
				goodsCartVO.setIsPackage(goods.getIsPackage());
			}
			if (goods.getIsWeight() == null) {
				goodsCartVO.setIsWeight(0);
			} else {
				goodsCartVO.setIsWeight(goods.getIsWeight());
			}
			goodsCartVO.setOriginalPrice(goods.getPrice());
			goodsCartVO.setPropIds("");
			goodsCartVO.setPropNames("");
			goodsCartVO.setPropPrice(0.0d);
			goodsCartVO.setSizeCount(goods.getSizeCount());
			goodsCartVO.setSizeId(goods.getSizeId());
			goodsCartVO.setSizeType(goods.getSizeType());
			goodsCartVO.setStoreId(storeId);

			SaveShopCartByUserVO userInfo = new SaveShopCartByUserVO();
			ThirdUserInfo thirdUserInfo = shopperInfoServiceApi.getThirdUserInfo(buyerId, authMode);
			if (thirdUserInfo != null) {
				userInfo.setAvatarPath(thirdUserInfo.getAvatar());
				userInfo.setBuyerId(buyerId);
				userInfo.setBuyNick(thirdUserInfo.getNickName() == null ? "吃货" : thirdUserInfo.getNickName());
			}
			goodsCartVO.setUserInfo(userInfo);

			DiscountInfoVO discountInfo = new DiscountInfoVO();

			List<DiscountInfo> discountInfoList = new ArrayList<DiscountInfo>();
			// 添加商品优惠信息
			if (shopper != null && !StringUtils.isEmpty(shopper.getShopId())) {
				discountInfoList = shopperGoodsServiceApi.getDiscountGoods(shopper.getShopId(), goodsId, nowDate,
						DateUtils.getDayofweek());
				if (!CollectionUtils.isEmpty(discountInfoList)) {
					DiscountInfo Info = discountInfoList.get(0);
					discountInfo.setDiscountInfo(Info.getDiscountInfo());
					discountInfo.setGoodsId(Info.getGoodsId());
					discountInfo.setIsSingleDiscount(Info.getIsSingleDiscount());
					discountInfo.setItemId(Info.getItemId());
					discountInfo.setItemType(Info.getItemType());
				}
			}
			goodsCartVO.setDiscountInfo(discountInfo);
			CoreResponse<SaveShopCartVO> saveCart = shopCartService.saveOrUpdateShopCartV2(goodsCartVO);
			if (saveCart != null && saveCart.getData().getSuccess()) {
				// 购物车页面
				path = sweepOrderVueUrl + "/#/shopCart?storeId=" + storeId + "&buyerId=" + buyerId + "&tableInfoId=null&source=" + 1+"&md=2";
			}
		} else {
			// 如果该商品有多个规格、或为套餐商品、有属性时则直接跳转到商品详情页
			path = sweepOrderVueUrl + "/#/goodsDetail?storeId=" + storeId + "&buyerId=" + buyerId + "&tableInfoId=null&goodsId="+ 
					+ sizeId + "&source=" + 1+"&md=2";
		}
		return path;
	}

	@Override
	public String getRedirectPath(Integer shopperId, Integer storeId, Integer tableInfoId, String buyerId,
		String accessToken,Integer orderSource,Integer source,String reserveHexiao,Integer bindType) {
	    int md = 2;
        if(new Integer(10).equals(bindType)){
            md = 4;
        }
        // 启动页路径
		String pathUrl = "/#/?buyerId=" + buyerId + "&tableInfoId=" + tableInfoId + "&storeId=" + storeId+"&md=" + md;
		//保存顾客微信扫码进入的accessToken,用于扫呗支付使用
		if(!StringUtils.isEmpty(accessToken)){
			redisService.setObj(buyerId+"_accessToken", accessToken, 24L, TimeUnit.HOURS);
		}
		//查询在线订单未核销订单
		List<WaimaiExtend> wiamaiExtend  = waimaiOrderService.getOnlineOrderHexiao(storeId,buyerId,null);
		if(!CollectionUtils.isEmpty(wiamaiExtend) && !"1".equals(reserveHexiao)){
			if(new Integer(1).equals(orderSource)){
				//在线订单自动核销页
				pathUrl ="/#/online/hexiaoList?storeId="+storeId+"&buyerId="+buyerId+"&tableInfoId=null&md=1";
			}else if(new Integer(0).equals(orderSource)){
				//在线订单历史订单页面
				pathUrl="/#/online/historyOrder?storeId="+storeId+"&buyerId="+buyerId+"&tableInfoId=null&hexiao=1&md=1";
			}else{
				//在线订单自动核销页
				pathUrl ="/#/online/hexiaoList?storeId="+storeId+"&buyerId="+buyerId+"&tableInfoId=null&md=1";
			}
			return sweepOrderVueUrl+pathUrl;
		}
		// 查询店铺是否开启扫码下单店铺装修配置
		ShopperConfig config = shopperInfoServiceApi.getShopperConfig(shopperId, "IS_OPEN_SWEEPORDER_DECORATION");
		int renovationShopper=0;
		if(config!=null){
			renovationShopper = config.getPropValue() != null ? Integer.valueOf(String.valueOf(config.getPropValue()))
					: 0;
		}
		// 获取店铺装修配置 是否显示启动页条件
		String pageCode = "P_Start_Up";
		String componentCode = "A_Page_Show";
		// 获取店铺装修配置 显示用餐人数页条件
		String pageCodeNum = "P_Meal_Numbers";
		String componentCodeNum = "A_Numbers_Show";
		String componentPageNum = "A_Numbers_Page";
		//店铺装修是否开启启动页
		Integer startCount = 0;
		//店铺装修是否开启人数选择页面
		Integer numberCount = 0;
		Integer componertCount = 0;
		String styleCode = "";
		//默认轻快餐模式
		Integer styleMode = 0;
		//小程序入口默认过滤店铺首页
		if((Constants.authMode.ALIPAY_MINI_AUTH.getValue()).equals(source) && !new Integer(1).equals(renovationShopper)){
			List <DecorationShopConfigDetailExtend> pageDetailDefault = shopperInfoServiceApi.getShopperDefaultPageDetail(0);
			for(DecorationShopConfigDetailExtend pageDetail:pageDetailDefault){
				//九宫格模式
				if(("P_Home").equals(pageDetail.getPageCode()) && ("A_Nine_Court_Mode").equals(pageDetail.getComponentCode())){
					styleMode = 1;
				}
				if (styleMode==1) {
					break;
				}
			}
			if(styleMode==1){
				//九宫格点餐页面路径
				pathUrl = "/#/home/goods/sudoku?storeId=" + storeId + "&buyerId=" + buyerId + "&tableInfoId=" + tableInfoId +"&md="+md;
			}else{
				//轻快餐点餐页面路径
				pathUrl = "/#/home/goods/index?storeId=" + storeId + "&buyerId=" + buyerId + "&tableInfoId=" + tableInfoId +"&md="+md;
			}
			return sweepOrderVueUrl+pathUrl;
			// 如果没有开通店铺装修功能则直接跳转到前端启动页
		}else if (!new Integer(1).equals(renovationShopper)) {
			pathUrl = sweepOrderVueUrl + pathUrl;
			//pathUrl = sweepOrderVueUrl + "/#/?buyerId=" + buyerId + "&tableInfoId=" + tableInfoId + "&storeId=" + storeId+"&md=1";
			return pathUrl;
		}
		// 查询是否绑定了店铺装修风格
		List<Long> list = shopperInfoServiceApi.getShopperRenovationByStoreId(storeId,0);
		ShopperConfigExtend shopperConfigExt = null;
		//获取店铺配置信息
		Map<String, Object> shopperConfig = shopperInfoServiceApi.getShopperAllConfig(storeId);
		if(shopperConfig == null){
			//店铺配置获取失败
			pathUrl = sweepOrderVueUrl+"/main.html#/error";;
			return pathUrl;
		}
		// map转成对象
		shopperConfigExt = SweepOrderUtils.convertToShopperConfigVO(shopperConfig);
		redisService.setObj(storeId + "_shopperConfig", shopperConfigExt,24L,TimeUnit.HOURS);	
		/*// 获取redis店铺配置信息
		Object configAll = redisService.getObj(storeId + "_shopperConfig");
		ShopperConfigExtend shopperConfigExt = null;
		if (configAll == null) {
			// 查询店铺所有配置
			Map<String, Object> shopConfig = shopperInfoServiceApi.getShopperAllConfig(storeId);
			// map转成对象
			shopperConfigExt = SweepOrderUtils.convertToShopperConfigVO(shopConfig);
		} else {
			shopperConfigExt = (ShopperConfigExtend) configAll;
		}*/
		if (!CollectionUtils.isEmpty(list)) {
			// 绑定了则查询商家自定义的店铺装修风格的启动页配置
			List <DecorationShopConfigDetailExtend> pageDetail = shopperInfoServiceApi.getShopperPageDetail(storeId,0);
			for (DecorationShopConfigDetailExtend page : pageDetail) {
				styleCode = page.getStyleCode();
				if (pageCode.equals(page.getPageCode()) && componentCode.equals(page.getComponentCode())) {
					startCount = 1;
				}
				if (pageCodeNum.equals(page.getPageCode()) && componentCodeNum.equals(page.getComponentCode())) {
					numberCount = 1;
				}
				if (pageCodeNum.equals(page.getPageCode()) && componentPageNum.equals(page.getComponentCode())) {
					componertCount = 1;
				}
				//九宫格模式
				if(("P_Home").equals(page.getPageCode()) && ("A_Nine_Court_Mode").equals(page.getComponentCode())){
					styleMode = 1;
				}
				if (startCount == 1 && numberCount == 1 && componertCount == 1 && styleMode==1) {
					break;
				}
			}
			// 绑定了则查询商家自定义的店铺装修风格的启动页配置
			if (startCount >= 1 && !(Constants.authMode.ALIPAY_MINI_AUTH.getValue()).equals(source)) {
				// 启动页路径
				pathUrl = "/#/?buyerId=" + buyerId + "&tableInfoId=" + tableInfoId + "&storeId=" + storeId +"&md="+md;
			} else {
				// 获取店铺装修配置 显示用餐人数页条件
				if (numberCount >= 1 && componertCount >= 1) {
					// 获取redis是否存在人数
					Integer peopleNumber = 0;
					if (tableInfoId != null) {
						if (shopperConfigExt != null && new Integer(1).equals(shopperConfigExt.getFirstPayMent()) && new Integer(1).equals(shopperConfigExt.getIsOpenDeskmateSinglePoint())) {
							peopleNumber = redisService.getObj(storeId + "_" + tableInfoId + "_" + buyerId + "_peopleNumber") == null ? 0
								: Integer.valueOf(String.valueOf(redisService.getObj(storeId + "_" + tableInfoId + "_" + buyerId +"_peopleNumber")));
						} else {
							peopleNumber = redisService.getObj(storeId + "_" + tableInfoId+"_peopleNumber") == null ? 0
								: Integer.valueOf(String.valueOf(redisService.getObj(storeId + "_" + tableInfoId+"_peopleNumber")));
						}
					} else {
						peopleNumber = redisService.getObj(storeId + "_" + buyerId) == null ? 0
							: Integer.valueOf(String.valueOf(redisService.getObj(storeId + "_" + buyerId+"_peopleNumber")));
					}
					// 如果存在人数就不需要再选择人数
					if (peopleNumber >= 1) { 
						pathUrl = redirectPathVue(storeId, tableInfoId, buyerId,styleCode,styleMode,bindType);
					} else {
						// 用餐人数页路径
						//pathUrl = "/#/chosePeopleNum?storeId=" + storeId + "&buyerId=" + buyerId + "&tableInfoId=" + tableInfoId +"&md=2";;
						//启动页
						pathUrl = "/#/?buyerId=" + buyerId + "&tableInfoId=" + tableInfoId + "&storeId=" + storeId +"&md=" + md;
					}
				} else {
					pathUrl = redirectPathVue(storeId, tableInfoId, buyerId,styleCode,styleMode,bindType);
				}
			}
		}else {
			// 没有绑定店铺装修、或者商品没有自定义配置店铺装修风格 查询默认配置
			List <DecorationShopConfigDetailExtend> pageDetailDefault = shopperInfoServiceApi.getShopperDefaultPageDetail(0);
			for(DecorationShopConfigDetailExtend pageDetail:pageDetailDefault){
				styleCode = pageDetail.getStyleCode();
				if (pageCode.equals(pageDetail.getPageCode()) && componentCode.equals(pageDetail.getComponentCode())) {
					startCount = 1;
				}
				if (pageCodeNum.equals(pageDetail.getPageCode()) && componentCodeNum.equals(pageDetail.getComponentCode())) {
					numberCount = 1;
				}
				if (pageCodeNum.equals(pageDetail.getPageCode()) && componentPageNum.equals(pageDetail.getComponentCode())) {
					componertCount = 1;
				}
				//九宫格模式
				if(("P_Home").equals(pageDetail.getPageCode()) && ("A_Nine_Court_Mode").equals(pageDetail.getComponentCode())){
					styleMode = 1;
				}
				if (startCount == 1 && numberCount == 1 && componertCount == 1 && styleMode==1) {
					break;
				}
			}
			// 显示启动页直接跳转启动页
			if (startCount >= 1 && !(Constants.authMode.ALIPAY_MINI_AUTH.getValue()).equals(source)) {
				// 启动页路径
				pathUrl = "/#/?buyerId=" + buyerId + "&tableInfoId=" + tableInfoId + "&storeId=" + storeId+"&md=" + md;;
			} else {
				// 显示用餐人数页直接跳转用餐人数页
				if (numberCount >= 1 && componertCount >= 1) {
					// 获取redis是否存在人数
					Integer peopleNumber = 0;
					if (tableInfoId != null) {
						if (shopperConfigExt != null && new Integer(1).equals(shopperConfigExt.getFirstPayMent()) && new Integer(1).equals(shopperConfigExt.getIsOpenDeskmateSinglePoint())) {
							peopleNumber = redisService.getObj(storeId + "_" + tableInfoId + "_" + buyerId) == null ? 0
								: Integer.valueOf(String.valueOf(redisService.getObj(storeId + "_" + tableInfoId + "_" + buyerId)));
						} else {
							peopleNumber = redisService.getObj(storeId + "_" + tableInfoId) == null ? 0
								: Integer.valueOf(String.valueOf(redisService.getObj(storeId + "_" + tableInfoId)));
						}
					} else {
						peopleNumber = redisService.getObj(storeId + "_" + buyerId) == null ? 0
							: Integer.valueOf(String.valueOf(redisService.getObj(storeId + "_" + buyerId)));
					}
					// 如果存在人数就不需要再选择人数
					if (peopleNumber >= 1) {
						pathUrl = redirectPathVue(storeId, tableInfoId, buyerId,styleCode,styleMode,bindType);
					} else {
						// 用餐人数页路径
						//pathUrl = "/#/chosePeopleNum?storeId" + storeId + "&buyerId=" + buyerId + "&tableInfoId=" + tableInfoId+"&md=2";;
						//启动页
						pathUrl = "/#/?buyerId=" + buyerId + "&tableInfoId=" + tableInfoId + "&storeId=" + storeId +"&md=" + md;
					}
				} else {
					pathUrl = redirectPathVue(storeId, tableInfoId, buyerId,styleCode,styleMode,bindType);
				}
			}
		}
		pathUrl = sweepOrderVueUrl + pathUrl;
		return pathUrl;
	}
	
	/**
	 * 判断VUE页面跳转路径
	 * 
	 * @param storeId
	 * @param tableInfoId
	 * @param buyerId
	 * @return
	 */
	public String redirectPathVue(Integer storeId, Integer tableInfoId, String buyerId,String styleCode,Integer styleMode,Integer bindType) {
	    int md = 2;
        if(new Integer(10).equals(bindType)){
            md = 4;
        }
        String pathUrl = "/#/?buyerId=" + buyerId + "&tableInfoId=" + tableInfoId + "&storeId=" + storeId +"&md="+md;
		// 查询是否直接进入购物车页
		String startDate = DateUtils.getYesterdayStartTime();
		String endDate = DateUtils.getTodayEndTime();
		DiningArea tableInfo = null;
		if (tableInfoId != null) {
			tableInfo = shopperInfoServiceApi.getDiningAreaById(tableInfoId);
		}
		if (tableInfo != null) {
			// 之所以改为先查询后更新,因为出现过根据非主键索引更新出现死锁情况
			List<GoodsCartAndDetail> cartList = goodsCartServiceApi.getGoodsCartByBuyerId(storeId, buyerId, startDate,
					endDate,4);
			int cartCount = 0;
			if (!CollectionUtils.isEmpty(cartList)) {
				List<Integer> cartId = new ArrayList<Integer>();
				for (GoodsCartAndDetail cart : cartList) {
					if (StringUtils.isEmpty(cart.getTableNo())) {
						cartId.add(cart.getId());
					}
				}
				// 将该用户在前台购物车中的购物车明细增加tableNo
				if (!CollectionUtils.isEmpty(cartId)) {
					cartCount = goodsCartServiceApi.updateGoodsCartForTableNo(cartId, tableInfo.getName());
				}
			}
			// 存在入座的 直接跳转购物车页面
			if (cartCount >= 1) {
				// 购物车页面路径
				pathUrl = "/#/shopCart?storeId=" + storeId + "&buyerId=" + buyerId + "&tableInfoId=" + tableInfoId +"&md="+md;
			} else {
				// 查询未完成订单 如果有则进入订单页
				Waimai waimai = waimaiOrderService.hasUnfinishedOrder(storeId, tableInfo.getName(),md);
				// 存在进行中订单时，直接跳转到进行中订单页
				if (waimai != null) {
					// 进行中订单页面路径
					pathUrl = "/#/orders?storeId=" + storeId + "&buyerId=" + buyerId + "&tableInfoId=" + tableInfoId + "&myOrder="
							+ waimai.getOrderNum()+"&md="+md;;
				} else {
					//通用版风格
					if(("S_Common").equals(styleCode)){
						if(styleMode==1){
							//九宫格点餐页面路径
							pathUrl = "/#/home/goods/sudoku?storeId=" + storeId + "&buyerId=" + buyerId + "&tableInfoId=" + tableInfoId +"&md="+md;
						}else{
							//轻快餐点餐页面路径
							pathUrl = "/#/home/goods/index?storeId=" + storeId + "&buyerId=" + buyerId + "&tableInfoId=" + tableInfoId +"&md="+md;
						}
					//增强版
					}else if(("S_Enhance").equals(styleCode)){
						//
						pathUrl = "/#/home/raster?storeId=" + storeId + "&buyerId=" + buyerId + "&tableInfoId=" + tableInfoId +"&md="+md;
					}
				}
			}
			// 桌台为空则直接跳转到点餐页面
		} else {
			//通用版风格
			if(("S_Common").equals(styleCode)){
				if(styleMode==1){
					//九宫格点餐页面路径
					pathUrl = "/#/home/goods/sudoku?storeId=" + storeId + "&buyerId=" + buyerId + "&tableInfoId=" + tableInfoId +"&md="+md;
				}else{
					//轻快餐点餐页面路径
					pathUrl = "/#/home/goods/index?storeId=" + storeId + "&buyerId=" + buyerId + "&tableInfoId=" + tableInfoId +"&md="+md;
				}
			//增强版
			}else if(("S_Enhance").equals(styleCode)){
				//
				pathUrl = "/#/home/raster?storeId=" + storeId + "&buyerId=" + buyerId + "&tableInfoId=" + tableInfoId +"&md="+md;
			}
		}
		return pathUrl;
	}

	@Override
	public String getRedirectOnlinePath(Integer storeId, String buyerId, Integer shopperId,String accessToken,Integer orderSource,Integer source,String reserveHexiao,Integer bindType) {
        int md = 2;
        //外卖
        if(new Integer(10).equals(bindType)){
            md = 4;
        }
	    String path ="";
		//保存顾客扫码进入在线订单的时间
		redisService.setObj(storeId+"_"+buyerId+"_scanTime", new Date(), 1L, TimeUnit.HOURS);
		ShopperConfigExtend shopperConfigExt = null;
		//获取店铺配置信息
		Map<String, Object> shopperConfig = shopperInfoServiceApi.getShopperAllConfig(storeId);
		if(shopperConfig==null){
			//店铺配置获取失败
			path ="/main.html#/error";
			return path;
		}
		// map转成对象
		shopperConfigExt = SweepOrderUtils.convertToShopperConfigVO(shopperConfig);
		redisService.setObj(storeId + "_shopperConfig", shopperConfigExt,24L,TimeUnit.HOURS);	
		/*Object config = redisService.getObj(storeId + "_shopperConfig");
		ShopperConfigExtend shopperConfigExt = null;
		if (config == null) {
			// 查询店铺所有配置
			Map<String, Object> shopperConfig = shopperInfoServiceApi.getShopperAllConfig(storeId);
			if(shopperConfig==null){
				//店铺配置获取失败
				path ="/#/error";
				return path;
			}
			// map转成对象
			shopperConfigExt = SweepOrderUtils.convertToShopperConfigVO(shopperConfig);
		} else {
			shopperConfigExt = (ShopperConfigExtend) config;
		}*/
		//保存顾客微信扫码进入的accessToken,用于扫呗支付使用
		if(!StringUtils.isEmpty(accessToken)){
			redisService.setObj(buyerId+"_accessToken", accessToken, 24L, TimeUnit.HOURS);
		}
		//查询在线订单未核销订单
		Waimai waimai = null;
		List<WaimaiExtend> wiamaiExtend  = waimaiOrderService.getOnlineOrderHexiao(storeId,buyerId,null);
		if(!CollectionUtils.isEmpty(wiamaiExtend) && !"1".equals(reserveHexiao)){
			//小程序入口
			if(new Integer(1).equals(orderSource)){
				//在线订单自动核销页
				path ="/#/online/hexiaoList?storeId="+storeId+"&buyerId="+buyerId+"&tableInfoId=null&md=1";
			}else if(new Integer(0).equals(orderSource)){
				//在线订单历史订单页面
				path="/#/online/historyOrder?storeId="+storeId+"&buyerId="+buyerId+"&tableInfoId=null&hexiao=1&md=1";
			}else{
				//判断该店铺下是否开通了图形模式（只要该店铺下另一一台机器开通了图形模式即认为该店开通了图形模式）
				boolean flag = shopperInfoServiceApi.getMachineConfig(storeId);
				if(!flag){
					//在线订单自动核销页
					path ="/#/online/hexiaoList?storeId="+storeId+"&buyerId="+buyerId+"&tableInfoId=null&md=1";
				}else{
					//在线订单历史订单页面
					path="/#/online/historyOrder?storeId="+storeId+"&buyerId="+buyerId+"&tableInfoId=null&hexiao=1&md=1";
				}
			}
			return path;
		}
		// 查询店铺配置白名单
		List<BusinessWhiteList> BusinessWhiteList = shopperInfoServiceApi.getShopperBusinessWhiteList(storeId,
				shopperId, CommConstant.WHILET_SWEEP_REPEAT_JUMP_PAGE);
		if (!CollectionUtils.isEmpty(BusinessWhiteList)) {
			WaimaiParam param = new WaimaiParam();
			param.setBuyerId(buyerId);
			param.setStoreId(storeId);
			param.setPayStatus(Constants.payStatus.PAYSTATUS_ONE.getValue());
			param.setStartDate(DateUtils.getBeforeDate(2));
			param.setEndDate(DateUtils.getNowTime());
			// add by yxy 2019年4月24日 17:35:50 查询两个小时内有已支付的订单（白名单）
			List<WaimaiExtend> waimaiList = waimaiServiceApi.getOnlineMealOrder(param);
			if (!CollectionUtils.isEmpty(waimaiList)) {
				// 在线订单历史订单页面
				path = "/#/online/historyOrder?storeId="+storeId+"&buyerId="+buyerId+"&tableInfoId=null&md=1";
				return path;
			}
		}
		WaimaiParam param = null;
		//查询是否存在扫码下单未支付订单
		param = new WaimaiParam();
		param.setBuyerId(buyerId);
		param.setStoreId(storeId);
		param.setOutSupportId(Constants.orderOutSupportId.SCAN_ORDER.getValue());
		//是否开启口碑正餐后付
		if(shopperConfigExt!=null && new Integer(1).equals(shopperConfigExt.getKoubeiDinner())){
			param.setOutSupportId(Constants.orderOutSupportId.KOUBEI_ORDER.getValue());
		}
		param.setStatus(Constants.orderStatus.STATUS_ONE.getValue());
		param.setPayStatus(Constants.payStatus.PAYSTATUS_ZERO.getValue());
		waimai = waimaiServiceApi.getWaimaiByBuyerId(param);
		if(waimai!=null && StringUtils.isEmpty(waimai.getTableUid())){
			DiningArea tableInfo =shopperInfoServiceApi.getDiningAreaByUid(waimai.getTableUid());
			if(tableInfo!=null){
				//扫码下单订单页
				path = "/#/orders?storeId=" + storeId + "&buyerId=" + buyerId + "&waimai=" + JSON.toJSONString(waimai) + "&myOrder="
						+ waimai.getOrderNum()+"&md=2";
				return path;
			}
		}
		
		//获取店铺配置是否开启智能取餐柜
		if(new Integer(1).equals(shopperConfigExt.getIntelligenceCabinet())){
			//查询是否存在
			param = new WaimaiParam();
			param.setBuyerId(buyerId);
			param.setStoreId(storeId);
			param.setOutSupportId(Constants.orderOutSupportId.ONLINE_ORDER.getValue());
			param.setPayStatus(Constants.payStatus.PAYSTATUS_ONE.getValue());
			param.setOrderType(2);
//			param.setPrepMealStatus(2);
			param.setStartDate(DateUtils.getBeforeDate(24));
			param.setEndDate(DateUtils.getNowTime());
			//查询24小时之内的取餐柜订单
			List<WaimaiExtend> waimaiList = waimaiServiceApi.getOnlineMealOrder(param);
			if(!CollectionUtils.isEmpty(waimaiList)){
				CupboardOrderRecord orderRecord = new CupboardOrderRecord();
				orderRecord.setOrderNum(waimaiList.get(0).getOrderNum());
				//查询柜子状态
				List<CupboardOrderRecord> orderRecordList = orderServiceApi.getOnlineMealRecordByNum(orderRecord);
				for(CupboardOrderRecord record:orderRecordList){
					if(new Integer(1).equals(record.getGoodStatus()) || new Integer(0).equals(record.getGoodStatus())){
						//进行中页面 取餐柜
						path = "/#/online/orders?storeId="+storeId+"&buyerId="+buyerId+"&tableInfoId=null&md=1";
						return path;
					}
				}
			}
		}
		//小程序入口默认进入人数选择页面
		if((Constants.authMode.ALIPAY_MINI_AUTH.getValue()).equals(source)){
			path = "/#/online/selectPeople?storeId="+storeId+"&buyerId="+buyerId+"&tableInfoId=null&md=1";
		}else{
			//如果是点餐页则需要根据装修平台配置显示页面
			path="/#/?storeId="+storeId+"&buyerId="+buyerId+"&tableInfoId=null&clientOrderMode=4&md=1";
		}
		// 查询店铺是否开启扫码下单店铺装修配置
		ShopperConfig configDec = shopperInfoServiceApi.getShopperConfig(shopperId, "IS_OPEN_SWEEPORDER_DECORATION");
		int renovationShopper=0;
		if(configDec!=null){
			renovationShopper = configDec.getPropValue() != null ? Integer.valueOf(String.valueOf(configDec.getPropValue()))
					: 0;
		}
		//小程序入口默认过滤店铺首页
		if ((Constants.authMode.ALIPAY_MINI_AUTH.getValue()).equals(source)
				&& !new Integer(1).equals(renovationShopper)) {
			path = "/#/online/selectPeople?storeId="+storeId+"&buyerId="+buyerId+"&tableInfoId=null&md=1";
			return path;
			// 如果没有开通店铺装修功能则直接跳转到前端启动页
		}else if (!new Integer(1).equals(renovationShopper)) {
			return path;
		}
		//path = "/#/?storeId="+storeId+"&buyerId="+buyerId+"&tableInfoId=null&clientOrderMode=4&md=1";
		// 查询是否绑定了店铺装修风格
		List<Long> list = shopperInfoServiceApi.getShopperRenovationByStoreId(storeId,1);
		// 获取店铺装修配置 是否显示启动页条件
		String pageCode = "P_Start_Up";
		String componentCode = "A_Page_Show";
		if (!CollectionUtils.isEmpty(list)) {
			// 绑定了则查询商家自定义的店铺装修风格的启动页配置
			Integer startCount = shopperInfoServiceApi.getShopperRenovationCustomPage(storeId, pageCode, componentCode,1);
			//如果开启了自定义开启了启动页
			if (startCount >= 1 && !(Constants.authMode.ALIPAY_MINI_AUTH.getValue()).equals(source)) {
				//启动页
				path = "/#/?storeId="+storeId+"&buyerId="+buyerId+"&tableInfoId=null&clientOrderMode=4&md=1";
			}else{
				//就餐前置页面
				//path = "/#/online/selectPeople?storeId="+storeId+"&buyerId="+buyerId+"&tableInfoId=null&md=1";
				path = "/#/?storeId="+storeId+"&buyerId="+buyerId+"&tableInfoId=null&clientOrderMode=4&md=1";
			}
		}
		return path;
	}

	@Override
	public String alipayAuth(Integer storeId, Integer shopperId, String authCode,Integer bindType) {
		try {
			AlipayClient alipayClient = AlipayAPIClientFactory.getAlipayClientSmallProgram();
			AlipaySystemOauthTokenRequest tokenRequest = new AlipaySystemOauthTokenRequest();
			tokenRequest.setGrantType(AlipayServiceEnvConstants.GRANT_TYPE.getValue());
			tokenRequest.setCode(authCode);
			// 根据authcode获取access_token
			AlipaySystemOauthTokenResponse tokenResponse = alipayClient.execute(tokenRequest);
			if (tokenResponse != null && tokenResponse.isSuccess()) {
				AlipayUserInfoShareRequest shareRequest = new AlipayUserInfoShareRequest();
				// 根据access_token获取用户信息
				AlipayUserInfoShareResponse shareResponse = alipayClient.execute(shareRequest,
						tokenResponse.getAccessToken());
				if (shareResponse != null && shareResponse.isSuccess()) {
					JSONObject userInfo = JSONObject.parseObject(shareResponse.getBody())
							.getJSONObject("alipay_user_userinfo_share_response");
					// 支付宝用户alipay_user_id
					String buyerId = null == userInfo.getString("alipay_user_id") ? ""
							: userInfo.getString("alipay_user_id");
					// 支付宝用户昵称
					String buyerNick = null == userInfo.getString("nick_name") ? "吃货" : userInfo.getString("nick_name");
					// 支付宝用户头像
					String avatarPath = null == userInfo.getString("avatar") ? "" : userInfo.getString("avatar");
					// 支付宝用户userId
					String userId = userInfo.getString("user_id");
					ThirdUserInfo thirdUserInfo = new ThirdUserInfo();
					thirdUserInfo.setAvatar(avatarPath);
					thirdUserInfo.setNickName(buyerNick);
					thirdUserInfo.setUserId(userId);
					thirdUserInfo.setThirdUserId(buyerId);
					// 用户信息来源 1支付宝
					thirdUserInfo.setSource(new Integer(1));
					// 保存支付宝用户信息
					shopperInfoServiceApi.saveOrUpdateThirdUserInfo(thirdUserInfo);
					//在线订单判断前端页面跳转路径（根据装修平台配置、是否存在订单判断）
					String pathUrl = getRedirectOnlinePath(storeId, buyerId,shopperId,null,null,null,null,bindType);
					return pathUrl;
				} else {
					System.out.println("调用失败");
				}
			} else {
				System.out.println("调用失败");
			}
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public String miniProgramRedirectPath(Integer storeId, Integer tableInfoId, Long thirdUserInfoId, String tableName,
			Integer orderSource,Integer source,Integer bindType) {
		String path = sweepOrderVueUrl+"/#/error";
		//获取第三方用户信息
		ThirdUserInfo thirdUserInfo = shopperInfoServiceApi.getThirdUserInfoById(thirdUserInfoId);
		if(thirdUserInfo == null || (thirdUserInfo.getThirdUserId() == null && thirdUserInfo.getUserId() == null)){
			logger.error("小程序获取前端地址异常msg=获取第三方用户信息异常storeId="+storeId+"thirdUserInfoId="+thirdUserInfoId);
			return path; 
		}
		String buyerId = "";
		if (!Utils.isEmpty(thirdUserInfo.getThirdUserId()) && Utils.isEmpty(thirdUserInfo.getUserId())) {
			buyerId = thirdUserInfo.getThirdUserId();
		}
		if (!Utils.isEmpty(thirdUserInfo.getUserId()) && Utils.isEmpty(thirdUserInfo.getThirdUserId())) {
			buyerId = thirdUserInfo.getUserId();
		}
		if (!Utils.isEmpty(thirdUserInfo.getThirdUserId()) && !Utils.isEmpty(thirdUserInfo.getUserId())) {
			buyerId = thirdUserInfo.getThirdUserId();
			if(thirdUserInfo.getThirdUserId().length() > thirdUserInfo.getUserId().length()){
				buyerId = thirdUserInfo.getUserId();
			}
		}
		//查询店铺配置信息
		Map<String, Object> shopperConfigMap = shopperInfoServiceApi.getShopperAllConfig(storeId);
		if(shopperConfigMap == null){
			logger.error("小程序获取前端地址异常msg=获取店铺配置信息异常storeId="+storeId);
			return path;
		}
		//查询店铺信息
		ShopperAndParent shopper = shopperInfoServiceApi.getShopperAndParent(storeId);
		if(shopper == null || shopper.getParentId() == null){
			logger.error("小程序获取前端地址异常msg=获取主店铺信息异常storeId="+storeId);
			return path;
		}
		Integer shopperId = shopper.getParentId();
		// 是否开通扫码下单，默认开启
		Object isSweepOrderObj = shopperConfigMap.get("CTR_SWEEP_ORDER");
		Integer isOpenSweepOrder = (null == isSweepOrderObj || StringUtils.isEmpty(isSweepOrderObj.toString())) ? 1
				: Integer.valueOf(isSweepOrderObj.toString());
		// 是否开启在线订单服务 默认开启
		Integer isOnlineOrder = shopperConfigMap.get("CTR_ONLINE_ORDER") == null ? 1
				: Integer.valueOf(String.valueOf(shopperConfigMap.get("CTR_ONLINE_ORDER")));
		
		DiningArea diningArea =null;
		//获取店铺桌台信息
		if (tableInfoId!=null) {
			diningArea = shopperInfoServiceApi.getDiningAreaById(tableInfoId);
		}else if(!StringUtils.isEmpty(tableName)){
			diningArea = shopperInfoServiceApi.getDiningAreaByTableName(tableName,storeId);
		}
		if (diningArea==null) {
			// 没有桌台且开通网络订单的则进入网络订单
			if (new Integer(1).equals(isOnlineOrder)) {
				path = sweepOrderVueUrl + getRedirectOnlinePath(storeId, buyerId, shopperId,null,orderSource,source,null,bindType);
				// 没有桌台未开通网络订单进入扫码下单预点单
			} else {
				path = getRedirectPath(shopperId, storeId, null, buyerId,null,orderSource,source,null,bindType);
			}
		} else {
			// 存在桌台的进去扫码下单桌台码
			if (new Integer(1).equals(isOpenSweepOrder)) {
				path = getRedirectPath(shopperId, storeId, tableInfoId, buyerId,null,orderSource,source,null,bindType);
			} else {
				logger.error("小程序获取前端地址异常msg=扫码桌台码时,未开通扫码下单storeId="+storeId+"isOpenSweepOrder="+isOpenSweepOrder);
				return path;
			}
		}
		return path;
	}
}